package com.taobao.server;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import com.taobao.client.Data;

/**
 * 创建url:获得sign签名
 * 
 * @author jiangyongyuan@use.com.cn
 * 
 */
public class UrlMaker {

	static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 获得调用url //
	 * appkey=test&timestamp=2008-01-11%2021:23:12&session=XXX&sign=XXX
	 * &format=html&v=1.0
	 * 
	 * @param params
	 * @param secret
	 * @param signName
	 * @return
	 */
	public static String getUrl(Map<String, String> params, String appkey,
			String secret, String session) {
		// http://127.0.0.1:8080/pageapitest/shoexLogon.jsp?appkey=wudangniu

		params.put("api_key", appkey);
		// params.put("appkey", appkey);
		params.put("timestamp", format.format(new Date()));
		params.put("session", session);
		params.put("format", "html");
		params.put("v", "1.0");

		for (Map.Entry<String, String> entry : params.entrySet()) {

			String key = entry.getKey();
			String value = entry.getValue();

			if (entry.getKey().indexOf("url") >= 0
					|| entry.getKey().indexOf("Url") >= 0) {
				if (value.indexOf("?") > 0)
					value = value.substring(0, value.indexOf("?"));

				if (value.indexOf("#") > 0)
					value = value.substring(0, value.indexOf("#"));

				if (key.equals("callback_url") || key.equals("url")) {
					
					if(value.indexOf("pageapi.html")>=0)
						value = value.substring(0, value.indexOf("pageapi.html"));
					
					if (value.endsWith("/"))
						value += "Result.html";
					else
						value += "/Result.html";
				}
			}
			params.put(key, value);
		}

		String signature = signature(params, secret, "sign");
		params.put("sign", signature);

		//encode the url
		for (Map.Entry<String, String> entry : params.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();

			if (entry.getKey().indexOf("url") >= 0
					|| entry.getKey().indexOf("Url") >= 0) {
				try {
					value = URLEncoder.encode(value, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				params.put(key, value);
			}
		}
		//end encode
		
		StringBuffer s = new StringBuffer();
		s.append(Data.url);
		s.append("?");
		StringBuffer ps = new StringBuffer();
		for (Map.Entry<String, String> entry : params.entrySet()) {

			String key = entry.getKey();
			String value = entry.getValue();

			if (entry.getKey().indexOf("url") >= 0
					|| entry.getKey().indexOf("Url") >= 0) {
				if (value.indexOf("?") > 0)
					value = value.substring(0, value.indexOf("?"));

				// if(value.indexOf("#")>0)
				// value = value.substring(0,value.indexOf("#"));
				//				
				// value += "/Result.html";
			}
			ps.append("&" + key + "=" + value);
		}
		return /* s.toString(); */(s.append(ps.substring(1))).toString();
	}

	/**
	 * 生成有效签名
	 * 
	 * @param params
	 * @param secret
	 * @return
	 */
	public static String signature(Map<String, String> params, String secret,
			String signName) {
		String result = null;
		if (params == null)
			return result;
		// remove sign parameter
		params.remove(signName);
		Map<String, String> treeMap = new TreeMap<String, String>();
		treeMap.putAll(params);
		Iterator<String> iter = treeMap.keySet().iterator();
		StringBuffer orgin = new StringBuffer(secret);
		while (iter.hasNext()) {
			String name = (String) iter.next();
			orgin.append(name).append(params.get(name));
		}
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			result = byte2hex(md.digest(orgin.toString().getBytes("utf-8")));
		} catch (Exception e) {
			throw new java.lang.RuntimeException("sign error !");
		}
		return result;
	}

	/**
	 * 二行制转字符串
	 * 
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}
}
